package com.ygqh.baby.service.wdtqyb.api;

import com.alibaba.fastjson.JSON;
import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.OrderDetailStatus;
import com.ygqh.baby.ao.OrderStatus;
import com.ygqh.baby.ao.RefundStatus;
import com.ygqh.baby.ao.ResponseEntity;
import com.ygqh.baby.handler.FortuneBagHandler;
import com.ygqh.baby.model.wdt.qyb.PushOrderToWdtBatchResult;
import com.ygqh.baby.model.wdt.qyb.PushOrderToWdtResult;
import com.ygqh.baby.model.wdt.qyb.WdtQybOrderReq;
import com.ygqh.baby.model.wdt.qyb.WdtQybResult;
import com.ygqh.baby.po.YgOrder;
import com.ygqh.baby.po.YgOrderDetail;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.service.YgOrderDetailService;
import com.ygqh.baby.service.YgOrderService;
import com.ygqh.baby.service.wdtqyb.builder.WdtOrderBuiler;
import com.ygqh.baby.service.wdtqyb.exception.WdtException;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 按商家推送订单到旺店通。
 */
@Component
public class WdtQybPushOrderByDetailApi extends WdtQybBaseApi {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private YgOrderDetailService ygOrderDetailService;
    @Autowired
    private YgOrderService ygOrderService;
    @Autowired
    private FortuneBagHandler fortuneBagHandler;


    /**
     * 推送订单到wdt 只做新增操作
     *
     * @param orderId    订单编号
     * @param supplierId 商家编号
     * @param shopNo     店铺编号
     * @return ResponseEntity
     */
    public ResponseEntity pushOrderToWdtBySupplier(Long orderId, Long supplierId, String shopNo) {
        logger.info("pushOrderToWdtBySupplier param : orderId=【{}】,supplierId=【{}】", orderId, supplierId);

        List<YgOrderDetail> details = ygOrderDetailService.findDetailsBySupplierId(orderId, supplierId);
        List<YgOrderDetail> waitingPushList = details.stream().filter(ygOrderDetail -> StringUtil.isNotBlank(ygOrderDetail.getOutCode())).collect(Collectors.toList());
        return pushOrderToWdtByDetail(orderId, waitingPushList, shopNo, false);
    }

    public ResponseEntity pushOrderToWdtBySupplier(Long supplierId, String shopNo) {
        logger.info("pushOrderToWdtBySupplier param :supplierId=【{}】", supplierId);
        List<YgOrder> orderList = ygOrderService.findOrderDetailBySupplier(supplierId, OrderDetailStatus.WaitingSend);
        return pushOrderToWdtBatch(shopNo, orderList, false);
    }

    /**
     * 按wdt单号推送 更新操作
     *
     * @param outCode 旺店通单号
     * @param shopNo  店铺编号
     * @return ResponseEntity
     */
    public ResponseEntity pushOrderToWdtByOutCode(String outCode, String shopNo) {
        logger.info("pushOrderToWdtByOutCode param : outCode=【{}】", outCode);
        List<YgOrderDetail> pushDetailList = ygOrderDetailService.findByOutCode(outCode);
        if (CollectionUtils.isEmpty(pushDetailList)) {
            return ResponseEntity.error("推送明细为空。");
        }
        Long orderId = pushDetailList.get(0).getOrderId();
        return pushOrderToWdtByDetail(orderId, pushDetailList, shopNo, false);
    }

    /**
     * 1.明细未推送，推送商家设置为壹果发货的明细
     * 2.明细已推送，更新操作
     *
     * @param shopNo 店铺编号
     * @param order  订单 含明细
     * @return ResponseEntity
     */
    public ResponseEntity pushOrderToWdt(String shopNo, YgOrder order) {
        return pushOrderToWdt(shopNo, order, true);
    }

    public ResponseEntity pushOrderToWdt(String shopNo, YgOrder order, Boolean onlyYiigoo) {
        fortuneBagHandler.reassemblyOrderDetails(order);
        return pushOrderToWdtByDetail(order, order.getOrderDetail(), shopNo, onlyYiigoo);
    }


    /**
     * 批量推送,
     * 1.明细未通过，推送商家设置为壹果发货的明细
     * 2.明细已推送，更新操作
     *
     * @param orderList 订单集合 含明细
     * @return ResponseEntity
     */
    public ResponseEntity pushOrderToWdtBatch(String shopNo, List<YgOrder> orderList) {
        return pushOrderToWdtBatch(shopNo, orderList, true);
    }

    public ResponseEntity pushOrderToWdtBatch(String shopNo, List<YgOrder> orderList, Boolean onlyYiigoo) {
        for (YgOrder ygOrder : orderList) {
            fortuneBagHandler.reassemblyOrderDetails(ygOrder);
        }
        if (CollectionUtils.isEmpty(orderList)) {
            return ResponseEntity.error("推送订单为空。", null);
        }
        List<WdtQybOrderReq> orderReqList = new ArrayList<>(orderList.size());

        PushOrderToWdtBatchResult pushOrderToWdtBatchResult = new PushOrderToWdtBatchResult();

        List<PushOrderToWdtResult> subResList = new ArrayList<>(orderList.size());
        for (int i = 0; i < orderList.size(); i++) {
            YgOrder o = orderList.get(i);
            if (StringUtil.isBlank(o.getUserName())) {
                YgUser user = ygUserService.findById(o.getUserId());
                o.setUserName(user.getUserName());
            }

            WdtOrderBuiler wdtOrderBuiler = getWdtOrderBuilderByOrder(o, onlyYiigoo);
            WdtQybOrderReq orderReq = wdtOrderBuiler.builder();
            PushOrderToWdtResult pushOrderToWdtResult = wdtOrderBuiler.buildPushResult();
            orderReqList.add(orderReq);
            subResList.add(pushOrderToWdtResult);
            if (orderReqList.size() == 30 || i == orderList.size() - 1) {
                ResponseEntity responseEntity = pushOrderToWdt(shopNo, orderReqList);
                if (responseEntity.isSuccess()) {
                    pushOrderToWdtBatchResult.addAllSuccess(subResList);
                } else {
                    subResList.forEach(res -> res.setMsg(responseEntity.getMsg()));
                    pushOrderToWdtBatchResult.addAllError(subResList);
                }
                subResList.clear();

            }
        }
        ResponseEntity responseEntity;
        if (CollectionUtils.isNotEmpty(pushOrderToWdtBatchResult.getErrorList())) {
            responseEntity = ResponseEntity.error(pushOrderToWdtBatchResult);
        } else {
            responseEntity = ResponseEntity.success(pushOrderToWdtBatchResult);
        }
        logger.info("pushOrderToWdtBatch result : 【{}】", JSON.toJSONString(responseEntity));
        return responseEntity;
    }


    private WdtOrderBuiler getWdtOrderBuilderByOrder(YgOrder order, Boolean onlyYiigoo) {
        List<YgOrderDetail> orderDetail = order.getOrderDetail();
        String[] outCodes = orderDetail.stream().filter(od -> StringUtil.isNotBlank(od.getOutCode())).map(YgOrderDetail::getOutCode)
                .distinct().toArray(String[]::new);
        if (outCodes.length > 1) {
            throw new RuntimeException("推送明细中存在多个旺店通订单，" + String.join(",", outCodes));
        }
        String tid;
        if (outCodes.length == 0) {
            if (onlyYiigoo) {
                orderDetail = getOrderDetailOnlyYiigoo(orderDetail);
            }
            int pushWdtTimes = ygOrderDetailService.getAlreadyPushWdtTimes(order.getOrderId());
            tid = WdtOrderBuiler.getOrderCodeToWdt(pushWdtTimes, order.getOrderId());
        } else {
            tid = orderDetail.get(0).getOutCode();
        }
        return new WdtOrderBuiler(order, orderDetail, tid);
    }

    private ResponseEntity pushOrderToWdtByDetail(Long orderId, List<YgOrderDetail> pushDetail, String shopNo, Boolean onlyYiigoo) {

        logger.info("pushOrderToWdtByDetail param : orderId=【{}】,pushDetail=【{}】", orderId, JSON.toJSONString(pushDetail));

        if (CollectionUtils.isEmpty(pushDetail)) {
            return ResponseEntity.error("该订单没有待推送明细，orderId= " + orderId);
        }
        YgOrder order = ygOrderService.findByOrderId(orderId);

        return pushOrderToWdtByDetail(order, pushDetail, shopNo, onlyYiigoo);
    }

    private ResponseEntity pushOrderToWdtByDetail(YgOrder order, List<YgOrderDetail> pushDetail, String shopNo, Boolean onlyYiigoo) {

        if (CollectionUtils.isEmpty(pushDetail)) {
            return ResponseEntity.error("该订单没有待推送明细，orderId= " + order.getOrderId());
        }
        if (StringUtil.isBlank(order.getUserName())) {
            YgUser user = ygUserService.findById(order.getUserId());
            order.setUserName(user.getUserName());
        }
        order.setOrderDetail(pushDetail);
        WdtOrderBuiler wdtOrderBuiler = getWdtOrderBuilderByOrder(order, onlyYiigoo);
        WdtQybOrderReq orderReq = wdtOrderBuiler.builder();
        PushOrderToWdtResult pushOrderToWdtResult = wdtOrderBuiler.buildPushResult();
        if (CollectionUtils.isEmpty(orderReq.getOrderList())) {
            return ResponseEntity.error("该订单没有待推送明细，orderId= " + order.getOrderId());
        }
        ResponseEntity responseEntity = pushOrderToWdt(shopNo, orderReq);
        if (!responseEntity.isSuccess()) {
            pushOrderToWdtResult.setMsg(responseEntity.getMsg());
        }
        responseEntity.setData(pushOrderToWdtResult);
        return responseEntity;
    }

    public ResponseEntity pushOrderToWdt(String shopNo, WdtQybOrderReq orderReq) {
        List<WdtQybOrderReq> list = new ArrayList<>();
        list.add(orderReq);
        return pushOrderToWdt(shopNo, list);
    }

    public ResponseEntity pushOrderToWdt(String shopNo, List<WdtQybOrderReq> orderReq) {
        if (StringUtil.isBlank(shopNo)) {
            shopNo = getShopNo();
        }
        logger.info("pushOrderToWdt param: shopNo=【{}】,orderReq=【{}】", shopNo, JSON.toJSONString(orderReq));
        try {
            WdtQybResult wdtQybResult = tradePush(shopNo, orderReq);
            logger.info("pushOrderToWdt result: 【{}】", JSON.toJSONString(wdtQybResult));
            return ResponseEntity.success();
        } catch (WdtException e) {
            logger.error("pushOrderToWdt error: 【{}】", e.getMessage(), e);
            return ResponseEntity.error(e.getErrorMsg());
        }
    }


    /**
     * 取消已推送的旺店通订单
     *
     * @param orderId 订单id
     * @return ResponseEntity
     */
    public ResponseEntity cancelWdtOrder(Long orderId) {
        YgOrder order = ygOrderService.findOrderDetailByOrderId(orderId);
        if (StringUtil.isBlank(order.getUserName())) {
            YgUser user = ygUserService.findById(order.getUserId());
            order.setUserName(user.getUserName());
        }
        fortuneBagHandler.reassemblyOrderDetails(order);
        List<YgOrderDetail> orderDetail = order.getOrderDetail();
        order.setOrderStatus(OrderStatus.TradeClosed);
        Map<String, List<YgOrderDetail>> collect = orderDetail.stream().filter(od -> od.getOutCode() != null).collect(Collectors.groupingBy(YgOrderDetail::getOutCode));

        PushOrderToWdtBatchResult pushOrderToWdtBatchResult = new PushOrderToWdtBatchResult();
        List<PushOrderToWdtResult> subResList = new ArrayList<>();
        for (Map.Entry<String, List<YgOrderDetail>> entry : collect.entrySet()) {
            List<YgOrderDetail> detailList = entry.getValue();
            detailList.forEach(od -> od.setRefundStatus(RefundStatus.RefundSuccess));
            WdtOrderBuiler wdtOrderBuiler = new WdtOrderBuiler(order, orderDetail, entry.getKey());
            WdtQybOrderReq orderReq = wdtOrderBuiler.builder();
            PushOrderToWdtResult pushOrderToWdtResult = wdtOrderBuiler.buildPushResult();
            subResList.add(pushOrderToWdtResult);
            String shopNo = getShopNo();
            System.out.println("=======================");
            System.out.println(JSON.toJSONString(orderReq));
            System.out.println("=======================");
            ResponseEntity responseEntity = pushOrderToWdt(shopNo, orderReq);
            if (responseEntity.isSuccess()) {
                pushOrderToWdtBatchResult.addAllSuccess(subResList);
            } else {
                subResList.forEach(res -> res.setMsg(responseEntity.getMsg()));
                pushOrderToWdtBatchResult.addAllError(subResList);
            }
            subResList.clear();
        }
        ResponseEntity responseEntity;
        if (CollectionUtils.isNotEmpty(pushOrderToWdtBatchResult.getErrorList())) {
            responseEntity = ResponseEntity.error(pushOrderToWdtBatchResult);
        } else {
            responseEntity = ResponseEntity.success(pushOrderToWdtBatchResult);
        }
        return responseEntity;

    }

    public ResponseEntity pushWdtOrderByStartTimes(Long orderId, int startTimes) {
        YgOrder order = ygOrderService.findOrderDetailByOrderId(orderId);
        if (StringUtil.isBlank(order.getUserName())) {
            YgUser user = ygUserService.findById(order.getUserId());
            order.setUserName(user.getUserName());
        }
        fortuneBagHandler.reassemblyOrderDetails(order);

        List<YgOrderDetail> orderDetail = order.getOrderDetail();
        orderDetail = getOrderDetailOnlyYiigoo(orderDetail);
        String tid = WdtOrderBuiler.getOrderCodeToWdt(startTimes, order.getOrderId());
        WdtOrderBuiler wdtOrderBuiler = new WdtOrderBuiler(order, orderDetail, tid);
        WdtQybOrderReq orderReq = wdtOrderBuiler.builder();
        PushOrderToWdtResult pushOrderToWdtResult = wdtOrderBuiler.buildPushResult();
        ResponseEntity responseEntity = pushOrderToWdt(getShopNo(), orderReq);
        if (!responseEntity.isSuccess()) {
            pushOrderToWdtResult.setMsg(responseEntity.getMsg());
        }
        responseEntity.setData(pushOrderToWdtResult);
        return responseEntity;

    }
}
